package unipi.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import unipi.database.ErrorCodes;
import unipi.database.User;
import unipi.helpers.ContactTypes;
import unipi.helpers.LoginCookie;
import unipi.helpers.Validator;

public class AddContact  extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	
	public AddContact()
	{
		super();
	}
	
	public void init() throws ServletException
	{
		
	
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		if(!LoginCookie.authCookie(request))
			response.sendRedirect("Login");
		else
		{
			String uid = LoginCookie.Get(request)[0];
			
			request.setCharacterEncoding("UTF-8");
			String contact = request.getParameter("contact");
			String type = request.getParameter("type");
			String label = request.getParameter("label");
			String message = "";
			
			if(contact != null && type != null && label != null)
			{			
				contact = Validator.escape(contact);
				type = Validator.escape(type);
				label = Validator.escape(label);
				
				ContactTypes ctype = type.equals(ContactTypes.Email.toString()) ? ContactTypes.Email : 
										  type.equals(ContactTypes.Phone.toString()) ? ContactTypes.Phone : 
										  ContactTypes.Other;
						
				ErrorCodes addContact = User.AddContactInfo(uid, contact, ctype, label);			
				
				message = addContact == ErrorCodes.OK?
												"Η επαφή προστέθηκε με επιτυχία":
												"Παρουσιάστηκε κάποιο πρόβλημα κατα την εισαγωγή της επαφής.";
			}
			else
			{
				message = "Παρουσιάστηκε καποιο πρόβλημα κατα την εισαγωγή της επαφής.";			
			}
			
			request.setAttribute("message", new String[]{"", "", message, ""});
			RequestDispatcher rq = request.getRequestDispatcher("Profile");
			rq.forward(request, response);
		}

	}
	
}
